p_needed <-
  c("viridis", "MASS", "sandwich", "lmtest", 
    "ggplot2", "patchwork", "dplyr","stargazer",
    "separationplot","car","reshape2","dagitty","boot","readxl")
packages <- rownames(installed.packages())
p_to_install <- p_needed[!(p_needed %in% packages)]
if (length(p_to_install) > 0) {
  install.packages(p_to_install)
}
sapply(p_needed, require, character.only = TRUE)
stargazer_opt <- ifelse(knitr::is_latex_output(), "latex", "html")

setwd("C:/Users/leons/Desktop/Paper/Analyse/Bachelor/BA/Data")
df <- read_xlsx("manifestos_coded_final.xlsx")

##############
#POPPA Grafik#
##############

setwd("C:/Users/leons/Desktop/Paper/Analyse/Bachelor/BA/POPPA")

library(dplyr)
library(tidyverse)
library(texreg)
library(haven)
library(ggplot2)
library(patchwork)

df_poppa <- read_dta("party_means.dta")

df1 <- df_poppa %>%
  filter(party_id >= 1201 & party_id <= 1207)

df1$party[df1$party == "B90Grune"] <- "B90-Die Grüne"

df1$party <- factor(df1$party,                                    # Factor levels in decreasing order
                    levels = df1$party[order(df1$populism, decreasing = TRUE)])

p1 <- ggplot(df1, aes(x = party, y = populism, fill = party)) + geom_bar(stat = "identity") +
  labs(title = "Populism in German parties",
       y = "Populism Score (0-10)",
       x = "Party") +
  scale_fill_manual("legend", values = c("AfD" = "#0099FF", "Linke" = "#FF66FF", "CSU" = "black", "SPD" = "#CC0000", "B90-Die Grüne" = "#339900", "CDU" = "black", "FDP" = "#FFFF00"))+
  theme_classic()+
  theme(legend.position = "none")

df1$party <- factor(df1$party,                                    # Factor levels in decreasing order
                    levels = df1$party[order(df1$lroverall, decreasing = TRUE)])

p2 <- ggplot(df1, aes(x = party, y = lroverall, fill = party)) + geom_bar(stat = "identity") +
  labs(title = "Ideological Stance of German parties",
       y = "Left-Right Score (0-10)",
       x = "Party") +
  scale_fill_manual("legend", values = c("AfD" = "#0099FF", "Linke" = "#FF66FF", "CSU" = "black", "SPD" = "#CC0000", "B90-Die Grüne" = "#339900", "CDU" = "black", "FDP" = "#FFFF00"))+
  theme_classic()+
  theme(legend.position = "none")

p1 + p2

#####################################
#Die Issues auf einen Nenner bringen#
#####################################

df <- df %>% mutate(Chapter = case_when(issue %in%c("Preamble", "Introduction", "Pre-Preamble")~"Preamble",
                                        issue %in%c("Summary", "Conclusion (Reached Goals)", "Retrospective", "Visions", "Conclusion (Successes)", "Conclusion (Promises)", "Conclusion","Future (Retirement, Migration, Democracy…)","Conclusion (Successes","Progress (Economy, Energy, Climate, Nature, Agricultre, Digitalization)","Development")~"Conclusion",
                                        issue %in%c("Democracy","Administration", "Democracy & Transparence", "Democracy & Freedom of Speech", "Democarcy", "Democracy & Rule of Law","Administration & Democracy", "Direct Democracy", "Democracy (Safety, Communes, Internet...)", "Democracy & Transparency","Democracy (Constitution, Safety, Privacy)", "Democracy (Justice, Digitalisation, Police, Crime)", "Democracy & Rights (Privacy, Police, anti-facism,  digitalization, cultre & media)","Democracy (Media, Crime)", "Democracy & Anti-Fascism", "Democracy & Diversity","Democracy (Migration, Women, Culture, Media, Homosexuality, Anti-Fascism, Police…)", "Democracy (Media, Religion, Police, Europe, Justice…)" ,"Democracy, Net Policy & Administration (Police, Safety, Drugs, Anti_Fascism…)")~"Democracy",
                                        issue %in%c("Finances", "Economy", "Household and Finances", "Economy  & Taxes", "Economy, Taxes & Budget", "Currency","Tourism & Gastronomy","Tourism","Economy & Budget","Budget & Finances","Economy & Finances","Budget","Economy (& Energy)","Taxes & Finances", "Labor & Economy","Taxes","Economy (Labor, Social)","Finances & Taxes","Finances, Investments & Public Agents","Economy & Structure","Tax Policy","Labour & Economy","Socio-Ecologic Economy (Labour, Tourism, Mobility…)","Economy & Labour","Suggestions for Financing")~"Economy & Finances",
                                        issue %in%c("Secularity","Law/Order", "Safety","Safety & Rule of Law","Safety, Justice & Privacy",  "Safty, Law & Order", "Domestic Policy (Safety)","Safety & Basic Rights", "Safety & Justice","Domestic Policy (Mostly Safety)","Domestic Policy, People*s Rights & Justice", "Domestic Policy", "Safety & Freedom", "Freedom & Safety","Justice") ~ "Domestic Policy, Safety, Law & Order",
                                        issue %in%c("Infrastructure","Infrastructure, Housing, Mobility","Traffic, Infrastructure and Development", "Infrastructure, Housing, Digitalisation","Infrastructure, Mobility & Digitalisation", "Digital Policy","Housing & Urban Planning", "Digitalisation","Traffic & Infrastructure","Mobility & Infrastructure",  "Traffic/Mobility", "Traffic & Environment",  "Constructing & City", "Mobility & Traffic","Digitalization","Mobility","Cities & Housing (Arts, Sports)","Traffic","Constructing, Housing & Development","City Development (Housing, Education, Mobility, Infrastructure…)","Development") ~ "Infrastructure, Mobility, Digitalisation & Development",
                                        issue %in%c("Corona", "Covid","Labor","Social","Health","Housing", "Building and Housing","Housing & Social","Health & Care","Social policy, Retirement, Labor & Insurance", "(Social &) Health Policy", "Health & Sports","Construction, Housing & Renting", "Welfare/Social","Family", "Family & Demography","Family & Youth", "Children  Youth","Elderly","Children & Youth","Youth","Generations (Elderly)","Youth & Social","Social (Sport, Culture, Labour, Housing, Inclusion, Youth, Health, Retirment...)","Social Justice & Healthcare","Equal Living","Poverty","Labor & Social","Construction & Housing","Social  (Commune, Retirment, Health, Housing)" ,"Social (Housing, Labor, Equality)","Renting & Housing","Social & Poverty","Labour", "Equal Conditions", "Labour & Life (Economy, Health, Elderly, Inclusion, Housing…)","Social Policy","Social Justice (Health, Children, Elderly, Families…)","Social (Labour, Health/Care, Children…)","Living Conditions (Health, Care, Mobility, Housing…)"   ) ~ "Social, Housing, Health & Labour",
                                        issue %in%c("Energy","Agriculture","Nature",  "Climate and Energy","Environment","Environment & Energy","Protection of the Coast", "Environment, Protection, Agriculture, Consumer protection","Energy, Technology & Traffic","Agriculture & Environment","Environment, Nature, Waste","Agriculture & Wine", "Energy & Mobility","Nature, Technology & Agriculture","Energy & Climate","Environmental Protection","Nature & Environment", "Agriculture, Environment & Nature Protection", "Climate, Energy, Technology & Digitalisation","Agriculture, Environmental & Consumer Protection", "Agriculture & Protection of Nature","Ecology (Nature, Energy, Mobility, Agriculture...)","Environment & Nature","Environment, Climate & Agricultre","Climate","Climate, Mobility & Agriculture","Climate, Environment & Energy","Climate, Enegery & Traffic","Agriculture, Environment, Nature & Consumers","Ecological Restructuring","Protection of Nature" ,"Climate & Environment","Sustainability (Animals, Climate, Agriculture, Energy)","Socio-Ecologic Renewal","Innovation", "Animals" )~"Sustainability",
                                        issue %in%c("Woman Policy and Gender","Freedom & Responsibility","Equality (Finances, Homosexuality, Crime, Emazipation...)","Female Policy & Genderideology","Gernder Policy","Queer Equality","Inclusion","Women's Rights","Anti-Discrimination (Fascism, Migration, Queer…)","Women's Rights, Discrimination & Equality (Migration)" ,"Equality (Sexuality, Youth, Elderly, Migration)","Women's Policy","Queer Policy","Inclusion & Accessiblity","Equality","Inclusive Society","Social Justice & Participation","Discrimination & Diversity","Fascism","Discrimination","Solidarity (Mobility, Housing, Culture…)","Diversity","Anti-Fascism & Basic Rights (Justice, Democracy, Migration…)","Social Justice","Solidarity, Progress, Justice","Emanzipation","Respect (Homosexuality)","Barrier Free (Inclusion)", "Peoples Rights","Consumer Rights")~"Identity Politics, Equality & Inclusion",
                                        issue %in%c("Education","Research","Culture","Culture, Media & Sports","Education, Science, Culture & Media","Education & University Policy","Support for Sports","Education & Research","Culture & Media","Sports","School & Education","Science & Research","Education, Science & Research","Art & Culture","Education & University","Children, Youth, Education & Science","Culture, Ideology & Memorials","Education & School","University & Science","Media","Universities","Culture, Media, Net Policy & Sports","Education, Culture, Sports & Media")~"Education, Research, Culture & Media",
                                        issue %in%c("Local","Communal","Countryside" ,"Communes","Local (Communes, Digitalization, Development, Industry","Regional (Housing, Mobility, Nature, Environment…)") ~ "Local",
                                        issue %in%c("Islam","Religion","Migration","Integration & Migration","Migration, Asylum, Nationality","Asylum & Migration","Migration & Integration","Asylum, Return & Integration","Qualified Migration & Integration","Migration, Asylum & Integration","Migration & Participation")~"Migration",
                                        issue %in%c("Catastrophes & Military","Foreign Policy","EU Policy","EU & Europe","Internationality (Peace, Migration, Europe, War, Military...)","Peace, Europe & Internationality","Military Expanditure & War","Peace, Military Expanditure & Conversion","Peace & Military Expanditure","Europe","Peace & Military","War & Peace","War, Peace, Military Expanditure", "Internationality","Peace, Internationality & Europe","Europe (Migration, Peace…)","Global")~"Foreign Politics & Europe"))

df <- df %>% mutate(EastWest = case_when(bl %in%c("Lower Saxony", "Bremen", "Hamburg", "Hesse", "Bavaria", "Rhineland Palatine", "Baden-Württembert", "Berlin", "Northrhine-Westphalia", "Schleswig Holstein", "Saarland")~"West",
                                         bl %in%c("Brandenburg", "Saxony", "Saxony-Anhalt", "Thurinigia", "Mecklenburg Western Pomerania")~"East"))


#####################
#Variablen erstellen#
#####################

df$pop <- ifelse(df$people_centrism == 1 & df$anti_elitism == 1, 1, 0)

require(stringr)
nwords <- function(string, pseudo=F){
  ifelse( pseudo,
          pattern <- "\\S+",
          pattern <- "[[:alpha:]]+"
  )
  str_count(string, pattern)
}

df$nwords <- nwords(df$text)

df <- df %>%
  group_by(bl,party,issue) %>%
  mutate(position_in_man_std = position_in_man/max(position_in_man),
         position_in_issue_std = position_in_issue/max(position_in_issue))


df2 <- df %>%
  group_by(bl,party,issue)%>%
  mutate(pop_prc_issue = sum(pop)/NROW(pop))

df2 <- df2 %>% mutate(Chapter = case_when(issue %in%c("Preamble", "Introduction", "Pre-Preamble")~"Preamble",
                                        issue %in%c("Summary", "Conclusion (Reached Goals)", "Retrospective", "Visions", "Conclusion (Successes)", "Conclusion (Promises)", "Conclusion","Future (Retirement, Migration, Democracy…)","Conclusion (Successes","Progress (Economy, Energy, Climate, Nature, Agricultre, Digitalization)","Development")~"Conclusion",
                                        issue %in%c("Democracy","Administration", "Democracy & Transparence", "Democracy & Freedom of Speech", "Democarcy", "Democracy & Rule of Law","Administration & Democracy", "Direct Democracy", "Democracy (Safety, Communes, Internet...)", "Democracy & Transparency","Democracy (Constitution, Safety, Privacy)", "Democracy (Justice, Digitalisation, Police, Crime)", "Democracy & Rights (Privacy, Police, anti-facism,  digitalization, cultre & media)","Democracy (Media, Crime)", "Democracy & Anti-Fascism", "Democracy & Diversity","Democracy (Migration, Women, Culture, Media, Homosexuality, Anti-Fascism, Police…)", "Democracy (Media, Religion, Police, Europe, Justice…)" ,"Democracy, Net Policy & Administration (Police, Safety, Drugs, Anti_Fascism…)")~"Democracy",
                                        issue %in%c("Finances", "Economy", "Household and Finances", "Economy  & Taxes", "Economy, Taxes & Budget", "Currency","Tourism & Gastronomy","Tourism","Economy & Budget","Budget & Finances","Economy & Finances","Budget","Economy (& Energy)","Taxes & Finances", "Labor & Economy","Taxes","Economy (Labor, Social)","Finances & Taxes","Finances, Investments & Public Agents","Economy & Structure","Tax Policy","Labour & Economy","Socio-Ecologic Economy (Labour, Tourism, Mobility…)","Economy & Labour","Suggestions for Financing")~"Economy & Finances",
                                        issue %in%c("Secularity","Law/Order", "Safety","Safety & Rule of Law","Safety, Justice & Privacy",  "Safty, Law & Order", "Domestic Policy (Safety)","Safety & Basic Rights", "Safety & Justice","Domestic Policy (Mostly Safety)","Domestic Policy, People*s Rights & Justice", "Domestic Policy", "Safety & Freedom", "Freedom & Safety","Justice") ~ "Domestic Policy, Safety, Law & Order",
                                        issue %in%c("Infrastructure","Infrastructure, Housing, Mobility","Traffic, Infrastructure and Development", "Infrastructure, Housing, Digitalisation","Infrastructure, Mobility & Digitalisation", "Digital Policy","Housing & Urban Planning", "Digitalisation","Traffic & Infrastructure","Mobility & Infrastructure",  "Traffic/Mobility", "Traffic & Environment",  "Constructing & City", "Mobility & Traffic","Digitalization","Mobility","Cities & Housing (Arts, Sports)","Traffic","Constructing, Housing & Development","City Development (Housing, Education, Mobility, Infrastructure…)","Development") ~ "Infrastructure, Mobility, Digitalisation & Development",
                                        issue %in%c("Corona", "Covid","Labor","Social","Health","Housing", "Building and Housing","Housing & Social","Health & Care","Social policy, Retirement, Labor & Insurance", "(Social &) Health Policy", "Health & Sports","Construction, Housing & Renting", "Welfare/Social","Family", "Family & Demography","Family & Youth", "Children  Youth","Elderly","Children & Youth","Youth","Generations (Elderly)","Youth & Social","Social (Sport, Culture, Labour, Housing, Inclusion, Youth, Health, Retirment...)","Social Justice & Healthcare","Equal Living","Poverty","Labor & Social","Construction & Housing","Social  (Commune, Retirment, Health, Housing)" ,"Social (Housing, Labor, Equality)","Renting & Housing","Social & Poverty","Labour", "Equal Conditions", "Labour & Life (Economy, Health, Elderly, Inclusion, Housing…)","Social Policy","Social Justice (Health, Children, Elderly, Families…)","Social (Labour, Health/Care, Children…)","Living Conditions (Health, Care, Mobility, Housing…)"   ) ~ "Social, Housing, Health & Labour",
                                        issue %in%c("Energy","Agriculture","Nature",  "Climate and Energy","Environment","Environment & Energy","Protection of the Coast", "Environment, Protection, Agriculture, Consumer protection","Energy, Technology & Traffic","Agriculture & Environment","Environment, Nature, Waste","Agriculture & Wine", "Energy & Mobility","Nature, Technology & Agriculture","Energy & Climate","Environmental Protection","Nature & Environment", "Agriculture, Environment & Nature Protection", "Climate, Energy, Technology & Digitalisation","Agriculture, Environmental & Consumer Protection", "Agriculture & Protection of Nature","Ecology (Nature, Energy, Mobility, Agriculture...)","Environment & Nature","Environment, Climate & Agricultre","Climate","Climate, Mobility & Agriculture","Climate, Environment & Energy","Climate, Enegery & Traffic","Agriculture, Environment, Nature & Consumers","Ecological Restructuring","Protection of Nature" ,"Climate & Environment","Sustainability (Animals, Climate, Agriculture, Energy)","Socio-Ecologic Renewal","Innovation", "Animals" )~"Sustainability",
                                        issue %in%c("Woman Policy and Gender","Freedom & Responsibility","Equality (Finances, Homosexuality, Crime, Emazipation...)","Female Policy & Genderideology","Gernder Policy","Queer Equality","Inclusion","Women's Rights","Anti-Discrimination (Fascism, Migration, Queer…)","Women's Rights, Discrimination & Equality (Migration)" ,"Equality (Sexuality, Youth, Elderly, Migration)","Women's Policy","Queer Policy","Inclusion & Accessiblity","Equality","Inclusive Society","Social Justice & Participation","Discrimination & Diversity","Fascism","Discrimination","Solidarity (Mobility, Housing, Culture…)","Diversity","Anti-Fascism & Basic Rights (Justice, Democracy, Migration…)","Social Justice","Solidarity, Progress, Justice","Emanzipation","Respect (Homosexuality)","Barrier Free (Inclusion)", "Peoples Rights","Consumer Rights")~"Identity Politics, Equality & Inclusion",
                                        issue %in%c("Education","Research","Culture","Culture, Media & Sports","Education, Science, Culture & Media","Education & University Policy","Support for Sports","Education & Research","Culture & Media","Sports","School & Education","Science & Research","Education, Science & Research","Art & Culture","Education & University","Children, Youth, Education & Science","Culture, Ideology & Memorials","Education & School","University & Science","Media","Universities","Culture, Media, Net Policy & Sports","Education, Culture, Sports & Media")~"Education, Research, Culture & Media",
                                        issue %in%c("Local","Communal","Countryside" ,"Communes","Local (Communes, Digitalization, Development, Industry","Regional (Housing, Mobility, Nature, Environment…)") ~ "Local",
                                        issue %in%c("Islam","Religion","Migration","Integration & Migration","Migration, Asylum, Nationality","Asylum & Migration","Migration & Integration","Asylum, Return & Integration","Qualified Migration & Integration","Migration, Asylum & Integration","Migration & Participation")~"Migration",
                                        issue %in%c("Catastrophes & Military","Foreign Policy","EU Policy","EU & Europe","Internationality (Peace, Migration, Europe, War, Military...)","Peace, Europe & Internationality","Military Expanditure & War","Peace, Military Expanditure & Conversion","Peace & Military Expanditure","Europe","Peace & Military","War & Peace","War, Peace, Military Expanditure", "Internationality","Peace, Internationality & Europe","Europe (Migration, Peace…)","Global")~"Foreign Politics & Europe"))
df2$incumb <- ifelse(df2$bl == "Thuringia" & df2$party == "LINKE" | df2$bl == "Brandenburg" & df2$party == "LINKE" | df2$bl == "Berlin" & df2$party == "LINKE", 1, 0)
df2$nwords <- nwords(df2$text)
df2$pop_prc_issue <- df2$pop_prc_issue*100

df22 <- df %>%
  group_by(bl,party,issue)%>%
  mutate(pop_prc_issue = sum(pop)/NROW(pop))
df22$pop_prc_issue <- df22$pop_prc_issue*100

df <- df %>%
  group_by(position_in_issue)%>%
  mutate(pop_prc_pos_issue = sum(pop)/NROW(pop))
df$pop_prc_pos_issue <- df$pop_prc_pos_issue*100

df <- df %>%
  group_by(bl,party)%>%
  mutate(pop_prc_bl = sum(pop)/NROW(pop))
df$pop_prc_bl <- df$pop_prc_bl*100

df <- df %>%
  group_by(party)%>%
  mutate(pop_prc_party = sum(pop)/NROW(pop))
df$pop_prc_party <- df$pop_prc_party*100

df <- df %>%
  group_by(party)%>%
  mutate(ant_prc_party = sum(anti_elitism)/NROW(anti_elitism))
df$ant_prc_party <- df$ant_prc_party*100

df <- df %>%
  group_by(party)%>%
  mutate(peop_prc_party = sum(people_centrism)/NROW(people_centrism))
df$peop_prc_party <- df$peop_prc_party*100

df$incumb <- ifelse(df$bl == "Thuringia" & df$party == "LINKE" | df$bl == "Brandenburg" & df$party == "LINKE" | df$bl == "Berlin" & df$party == "LINKE", 1, 0)

#Making a reference
df$reference <- ifelse(df$Chapter == "Social, Housing, Health & Labour", "Social, Housing, Health & Labour",
                       ifelse(df$Chapter == "Identity Politics, Equality & Inclusion", "Identity Politics, Equality & Inclusion",
                              ifelse(df$Chapter=="Democracy","Democracy",
                                     ifelse(df$Chapter == "Conclusion","Conclusion",
                                            ifelse(df$Chapter == "Preamble","Preamble",
                                                   ifelse(df$Chapter == "Economy & Finances","Economy & Finances",
                                                          ifelse(df$Chapter == "Foreign Politics & Europe","Foreign Politics & Europe",
                                                                 ifelse(df$Chapter == "Migration","Migration",
                                                                        ifelse(df$Chapter == "Local","Reference Issue",
                                                                               ifelse(df$Chapter=="Education, Research, Culture & Media", "Reference Issue",
                                                                                      ifelse(df$Chapter=="Sustainability","Reference Issue",
                                                                                             ifelse(df$Chapter=="Infrastructure, Mobility, Digitalisation & Development","Reference Issue",
                                                                                                    ifelse(df$Chapter=="Domestic Policy, Safety, Law & Order","Reference Issue","Error")))))))))))))
table(df$reference)

######################
#Deskriptive Analysen#
######################

df1 <- df %>% group_by(party) %>% summarise(me = mean(pop_prc_party))
df11 <- df %>% group_by(party) %>% summarise(me = mean(ant_prc_party))
df12 <- df %>% group_by(party) %>% summarise(me = mean(peop_prc_party))

p0<-ggplot(df1, aes(x=party, y=me, fill=party)) +
  geom_bar(stat="identity", color=c("#0066FF", "#FF0066"), fill=c("#0066FF", "#FF0066")) +
  geom_text(aes(label=sprintf("%2.0f%%", round(me, digits = 2))), position=position_stack(vjust=0.5), color="white", size = 6) +
  scale_fill_manual(values=c("#0066FF", "#FF0066")) +
  labs(x="", y="Proportions (%)", title="Fig. A1 - Mean percentage of Populist Paragraphs") +
  ylim(0, 30) +
  theme_minimal()

p1 <- ggplot(df11, aes(x=party, y=me, fill=party)) +
  geom_bar(stat="identity", color=c("#0066FF", "#FF0066"), fill=c("#0066FF", "#FF0066")) +
  geom_text(aes(label=sprintf("%2.0f%%", round(me, digits = 2))), position=position_stack(vjust=0.5), color="white", size = 6) +
  scale_fill_manual(values=c("#0066FF", "#FF0066")) +
  labs(x="", y="", title="Fig. A2 - Mean percentage of Anti-Elitist Paragraphs") +
  ylim(0, 35) +
  theme_minimal()

p2 <- ggplot(df12, aes(x=party, y=me, fill=party)) +
  geom_bar(stat="identity", color=c("#0066FF", "#FF0066"), fill=c("#0066FF", "#FF0066")) +
  geom_text(aes(label=sprintf("%2.0f%%", round(me, digits = 2))), position=position_stack(vjust=0.5), color="white",size = 6) +
  scale_fill_manual(values=c("#0066FF", "#FF0066")) +
  labs(x="", y="", title="Fig. A3 - Mean percentage of People Centrist Paragraphs") +
  ylim(0, 35) +
  theme_minimal()

p0+p1+p2

df23 <- df22 %>% group_by(Chapter,party) %>% summarise(me = mean(pop_prc_issue))
p3 <- ggplot(aes(x =reorder(Chapter, +me), y = me, fill = party), data = df23) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "Average percentage of populist paragraphs by chapter",
       x = "",
       y = "% of populist paragraphs",
       fill = "Party") +
  scale_fill_manual(values = c("#0066FF", "#FF0066"))+
  theme_classic() +
  coord_flip()+
  theme(axis.text.x = element_text( hjust=1), legend.position = "right")


df3 <- df %>% group_by(bl,party) %>% summarise(me = mean(pop_prc_bl))
ggplot(aes(x = reorder(bl, +me), y = me, fill = party), data = df3) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "Average percentage of populist paragraphs by federal state",
       x = "",
       y = "% of populist paragraphs",
       fill = "Party") +
  scale_fill_manual(values = c("#0066FF", "#FF0066"))+
  theme_classic()+
  coord_flip()+
  theme(axis.text.x = element_text( hjust=1), legend.position = "right")

dfcount <- df %>%
  group_by(party,year,Chapter) %>%
  summarise(n_paragraphs = n(), .groups = "drop")

ggplot(dfcount, aes(x=reorder(Chapter, +n_paragraphs),y=n_paragraphs, fill = party)) +
  geom_boxplot() +
  labs(title = "Number of paragraphs by party and issue",
       x = "",
       y = "Number of Paragraphs",
       fill = "Party") +
  scale_fill_manual(values = c("#0066FF", "#FF0066"))+
  theme_classic()+
  coord_flip()



#df4 <- df %>% group_by(position_in_issue) %>% summarise(me = mean(pop_prc_pos_issue))
#p4 <-ggplot(aes(x =position_in_issue, y = me), data = df4) + geom_point(stat = "identity") +
#  labs(title = "Average percentage of populist paragraphs by position",
#       x = "Position in issue",
#       y = "% of populist paragraphs") +
#  theme_classic()+
#  ylim(0,25)+
#  geom_smooth()

#p3+p4

############################
#Overlap between Variables?#

# Create the contingency table
contingency_table <- table(df$people_centrism, df$pop_sov)

# Convert the contingency table to a data frame
df_heatmap <- as.data.frame(as.table(contingency_table))

# Create the Heatmap
ggplot(df_heatmap, aes(x=Var1, y=Var2, fill=Freq)) +
  geom_tile() +
  geom_text(aes(label=Freq), color="white", size=6) +  # Add frequencies to each square
  scale_fill_gradient(low = "black", high = "lightgrey") +
  scale_x_discrete(labels=c("0" = "No", "1" = "Yes")) +  # Change x-axis labels
  scale_y_discrete(labels=c("0" = "No", "1" = "Yes")) +  # Change y-axis labels
  theme_minimal() +
  labs(x="People-Centrism", y="Popular Sovereignty", fill="Frequency", title = "Overlap between people-centrism and popular sovereignty as dimensions")



######################
#Statistische Modelle#
######################

df$Chapter <- as.factor(df$Chapter)
df$Chapter <- relevel(df$Chapter, ref = "Preamble")
df2$Chapter <- as.factor(df2$Chapter)
df2$Chapter <- relevel(df2$Chapter, ref = "Preamble")

m1 <- glm(pop ~ Chapter,df, family = binomial("logit"))
m2 <- glm(pop ~ Chapter+position_in_man_std + position_in_issue_std,df, family = binomial("logit"))
m3 <- glm(pop ~ Chapter+position_in_man_std + position_in_issue_std+party+EastWest,df, family = binomial("logit"))
m4 <- glm(pop ~ Chapter+position_in_man_std + position_in_issue_std+party+EastWest+incumb + nwords,df, family = binomial("logit"))

#m2 <- glm(anti_elitism ~ Chapter+party+EastWest+incumb + nwords +position_in_man_std + position_in_issue_std,df, family = binomial("logit"))
#m3 <- glm(people_centrism ~ Chapter+party+EastWest+incumb + nwords +position_in_man_std + position_in_issue_std,df, family = binomial("logit"))
#m4 <- lm(pop_prc_issue ~ Chapter + party + EastWest + incumb,df2)
m5 <- glm(pop ~ Chapter*party+EastWest+incumb + nwords +position_in_man_std + position_in_issue_std,df, family = binomial("logit"))
m6 <- lm(pop_prc_issue ~ Chapter * party + EastWest + incumb,df2)

stargazer(
  list(m1, m2, m3, m4),
  out = "table.tex",
  title = "Logistic Regression Results",
  intercept.bottom = TRUE,
  covariate.labels = c(
    "Chapter: Conclusion",
    "Chapter: Democracy",
    "Chapter: Domestic Policy, Safety, Law & Order",
    "Chapter: Economy & Finance",
    "Chapter: Education, Research, Culture & Media",
    "Chapter: Foreign Politics, Equality & Inclusion",
    "Chapter: Identity Politics, Equality & Inclusion ",
    "Chapter: Infrastructure, Mobility, Digitalization & Development",
    "Chapter: Local",
    "Chapter: Migration",
    "Chapter: Social, Housing, Health & Labour",
    "Chapter: Sustainability",
    "Party: DIE LINKE",
    "Western Germany",
    "Incumbency: Yes",
    "Position in Manifesto (std.)",
    "Position in Issue (std.)"
  ),
  dep.var.labels = c("POP",
                     "Anti-Elit.",
                     "Peop. centr.",
                     "%POP"),
  table.placement = "h", # latex output, keep the figure here in text
  type = "latex",
  omit = c("bl", "nwords")
)

######################
#Statistische Modelle#
######################

#Mit alternativer Chapter Variable

df$reference <- as.factor(df$reference)
df$reference <- relevel(df$reference, ref = "Reference Issue")
df$incumb <- as.factor(df$incumb)

m1 <- glm(pop ~ reference,df, family = binomial("logit"))
m2 <- glm(pop ~ reference+position_in_man_std + position_in_issue_std,df, family = binomial("logit"))
m3 <- glm(pop ~ reference+position_in_man_std + position_in_issue_std+party+EastWest+incumb + nwords,df, family = binomial("logit"))
m4 <- glm(pop ~ reference*party+position_in_man_std + position_in_issue_std+EastWest+incumb + nwords,df, family = binomial("logit"))

stargazer(
  list(m1, m2, m3, m4),
  out = "table.tex",
  title = "Logistic Regression Results",
  intercept.bottom = TRUE,
  covariate.labels = c(
    "Chapter: Conclusion",
    "Chapter: Democracy",
    "Chapter: Economy & Finances",
    "Chapter: Foreign Politics & Europe",
    "Chapter: Identity Politics, Equality & Inclusion",
    "Chapter: Migration",
    "Chapter: Preamble",
    "Chapter: Social, Housing, Health & Labour",
    "Position in Manifesto (Std.)",
    "Position in Issue (Std.)",
    "Party: Die LINKE",
    "Western Germany",
    "Incumbency: Yes",
    "Number of Words",
    "Conclusion * Die LINKE",
    "Democracy * Die LINKE",
    "Economy * Die LINKE",
    "Foreign Politics * Die LINKE",
    "Identity Politics * Die LINKE",
    "Migration * Die LINKE",
    "Preamble * Die LINKE",
    "Social * Die LINKE"
  ),
  dep.var.labels = c("Model 1",
                     "Model 2",
                     "Model 3",
                     "Model 4"),
  table.placement = "h", # latex output, keep the figure here in text
  type = "latex"
)


##################
#Simulationen#####
##################
m4 <- glm(pop ~ reference*party+position_in_man_std + position_in_issue_std+EastWest+incumb + nwords,df, family = binomial("logit"))

#Simulation:
beta_hat <- coef(m4) 
V_hat <- vcov(m4)    
nsim <- 10000        
S <- mvrnorm(n = nsim, 
             mu = beta_hat, 
             Sigma = V_hat) 
coef(m4)
table(df$Chapter)
scenario_1 <- cbind(1, diag(1, nrow = 8),1,mean(df$position_in_man_std), mean(df$position_in_issue_std), 1, 0, mean(df$nwords), diag(1, nrow = 8)*1)
scenario_1r <- cbind(1, 0,0,0,0,0,0,0,0,1,mean(df$position_in_man_std), mean(df$position_in_issue_std), 1, 0, mean(df$nwords), 0,0,0,0,0,0,0,0)

Xbeta1 <- cbind(S %*% t(scenario_1r), S %*% t(scenario_1))

#Now we create the CDF
p_sim1 <- plogis(Xbeta1)

#Now we compute the means and quantiles for our predicted probabilites
p_mean1 <- apply(p_sim1, 2, mean)
p_qu1 <- t(apply(p_sim1, 2, quantile, prob = c(0.025, 0.975), na.rm = T))

#Now we repeat this process for the scenario with the AfD
scenario_2 <- cbind(1, diag(1, nrow = 8),0,mean(df$position_in_man_std), mean(df$position_in_issue_std), 1, 0, mean(df$nwords), diag(1, nrow = 8)*0)
scenario_2r <- cbind(1, 0,0,0,0,0,0,0,0,0,mean(df$position_in_man_std), mean(df$position_in_issue_std), 1, 0, mean(df$nwords), 0,0,0,0,0,0,0,0)

Xbeta2 <- cbind(S %*% t(scenario_2r), S %*% t(scenario_2))

p_sim2 <- plogis(Xbeta2)

p_mean2 <- apply(p_sim2, 2, mean)
p_qu2 <- t(apply(p_sim2, 2, quantile, prob = c(0.025, 0.975), na.rm = T))


par(mar = c(6, 7, 4, 2) + 0.1)
plot(y = 0:8, 
     x = p_mean2,
     type="n",
     xlim = c(0,0.5),
     main = "Predicted Probabilities for a Populist Paragraph",
     xlab = "Probability for a Populist Paragraph",
     ylab = "",
     bty = "n",
     yaxt = "n",
     las = 1)

offset <- 0.15

points(y = 0:8 - offset,                                #The line of predicted probabilities
       x = p_mean1,
       lwd = 2,
       col="#FF0066",
       cex = 1.5)

segments(y0 = 0:8 - offset,
         y1 = 0:8 - offset,
         x0 = p_qu1[,1],
         x1 = p_qu1[,2],
         lwd = 2,
         col = "#FF0066")

points(y = 0:8 + offset, 
       x = p_mean2,
       lwd = 2,
       col="#0066FF",
       cex = 1.5)

segments(y0 = 0:8 + offset,
         y1 = 0:8 + offset,
         x0 = p_qu2[,1],
         x1 = p_qu2[,2],
         lwd = 2,
         col = "#0066FF")

categories <- c("Non-Hypotheses Issues","Conclusion","Democracy","Economy","Foreign","Identity","Migration","Preamble","Social")
axis(2, at = 0:8, labels = categories, las = 2, cex.axis = 0.6, srt = 45)  # Rotate and add X-axis labels

legend("topright",
       col = c("#FF0066",  
               "#0066FF"),
       lty = c("solid",  
               "solid"),
       legend = c("Die Linke",
                  "AfD"),
       bty = "n",
       cex = 0.85)
